<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/11
 * Time: 17:57
 */

namespace App\Service;


use App\Models\Administrator;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

class AdministratorService
{
    /**
     * 获取管理用户列表
     * @param array $params
     * @param string $orderBy
     * @param string $sort
     * @param int $page
     * @param int $limit
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getList($params = [],$orderBy = 'id',$sort = 'DESC',$page = 1,$limit = 10)
    {
        $where = [];
//        $administrator = new Administrator();
        if(isset($params['username']) && !empty($params['username'])){
            $where[] = ['username','like',"%{$params['username']}%"];
        }
        $start=($page-1)*$limit;
        $list = Administrator::with(['roles'])->where($where)->skip($start)->take($limit)->orderBy($orderBy,$sort)->get(['id','name','username','avatar','status','created_at','updated_at'])->toArray();
        $count = Administrator::where($where)->count();
        $pageCount = ceil($count/$limit);
        $data = [
            'list'          => $list,
            'pageCount'     => $pageCount,
        ];
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }

    /**
     * 获取全部的员工
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getAllUser()
    {
        $list = Administrator::where('id','>',1)->get(['id','username','name'])->toArray();
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$list]);
    }

    /**
     * 通过管理用户ID获取用户信息
     * @param int $userId
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getUserById($userId = 0)
    {
        $info = Administrator::with(['roles'])->where('id',$userId)->first(['id','name','username','avatar','status','created_at','updated_at']);
        $info = $info ? $info->toArray() : [];
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$info]);
    }

    /**
     * 添加
     * @param array $params
     * @return \Illuminate\Http\JsonResponse
     */
    public static function add($params = [])
    {
        try{
            if(Administrator::where('username',trim($params['username']))->first()){
                throw new \Exception('该用户名已存在');
            }
            $info = Administrator::create(['username'=>trim($params['username']),'name'=>trim($params['name']),'password'=>bcrypt(trim($params['password'])),'status'=>intval($params['status'])]);
            if(!$info){
                throw new \Exception('新增管理员失败');
            }
            if(isset($params['role_ids']) && !empty($params['role_ids'])){
                $insertData = [];
                $roleIdArr = is_array($params['role_ids']) ? $params['role_ids'] : [$params['role_ids']];
                foreach($roleIdArr as $v){
                    $insertData[] = [
                        'role_id'   => $v,
                        'user_id'   => $info->id,
                        'created_at'    => date('Y-m-d H:i:s'),
                        'updated_at'    => date('Y-m-d H:i:s'),
                    ];
                }
                DB::table('admin_role_users')->insert($insertData);
            }
        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'添加管理员成功']);
    }

    /**
     * 修改
     * @param array $params
     * @return \Illuminate\Http\JsonResponse
     */
    public static function edit($params = [])
    {
        try{
            $info = Administrator::where('id',intval($params['id']))->first();
            if(!$info){
                throw new \Exception('该管理员不存在');
            }
            $info->username = trim($params['username']);
            $info->name     = trim($params['name']);
            if(!empty(trim($params['password']))){
                $info->password = bcrypt(trim($params['password']));
            }
            $info->status = intval($params['status']);
            $save = $info->save();
            if(!$save){
                throw new \Exception('修改失败');
            }
            $idArr = DB::table('admin_role_users')->where('user_id',$info->id)->pluck('role_id');
            $idArr = $idArr ? $idArr->toArray() : [];
            if(!empty($params['role_ids'])){
                $roleIdArr = is_array($params['role_ids']) ? $params['role_ids'] : [$params['role_ids']];
                foreach($roleIdArr as $v){
                    if(!empty($idArr) && in_array($v,$idArr)){
                        unset($idArr[array_search($v,$idArr)]);
                    }else{
                        DB::table('admin_role_users')->insert(['role_id'=>$v,'user_id'=>$info->id,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')]);
                    }
                }
            }
            if(!empty($idArr)){
                DB::table('admin_role_users')->where('user_id',$info->id)->whereIn('role_id',$idArr)->delete();
            }
        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'修改成功']);
    }
    
    public static function checkStatus()
    {
        try{
            $info = Administrator::where('id',intval($params['id']))->first();
            if(!$info){
                throw new \Exception('该管理员不存在');
            }
            $info->status = intval($params['status']);
            $save = $info->save();
            if(!$save){
                throw new \Exception('更改状态失败');
            }
        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'更改状态成功']);   
    }

    /**
     * 删除
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public static function destroy($id)
    {
        $idArr = is_array($id) ? $id : [$id];
        if(!$idArr){
            return Response()->json(['code'=>201,'msg'=>'请选择要删除的管理员']);
        }
        if(in_array(1,$idArr)){
            return Response()->json(['code'=>201,'msg'=>'超级管理员不能删除']);
        }
        $del = Administrator::destroy($idArr);
        if($del){
            return Response()->json(['code'=>200,'msg'=>'删除成功']);
        }
        return Response()->json(['code'=>201,'msg'=>'删除失败']);
    }

}
